<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     
      <el-form-item label="主表名称" prop="majorName">
        <el-input
          v-model="queryParams.majorName"
          placeholder="请输入主表名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="!detailDialog.isDisabled">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['grc:fileInfo:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['grc:fileInfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['grc:fileInfo:remove']"
          >删除</el-button
        >
      </el-col>
      
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="fileInfoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
       <el-table-column label="文件id" align="center" prop="fileId" />

     
       <el-table-column label="主表id" align="center" prop="majorId" />
        <el-table-column label="主表名称" align="center" prop="majorName" />


      
      <el-table-column label="文件名称" align="center" prop="fileName" />
     
      <el-table-column label="文件大小" align="center" >
        <template slot-scope="scope">
         {{ parseInt(scope.row.fileSize /1024 ) }} KB
        
        </template>
      </el-table-column>
     
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="160"
        v-if="!detailDialog.isDisabled"
      >
        
        <template slot-scope="scope">

        
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDownload(scope.row)"
            v-hasPermi="['grc:fileInfo:edit']"
            >下载</el-button
          >
           <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDownload2(scope.row)"
            v-hasPermi="['grc:fileInfo:edit']"
            >下载2</el-button
          >
          

           <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['grc:fileInfo:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['grc:fileInfo:remove']"
            >删除</el-button
          >

       


          
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改附件信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      @close="pageClose"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :disabled="pageDisabled"
        label-width="190px"
      >
         <el-upload
          ref="upload"
          :limit="3"
           accept=".jpg, .png, .docx"
          :action="upload.url"
          :headers="upload.headers"
          :file-list="upload.fileList"
          :on-preview="handlePreview"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"

          :before-remove="beforeRemove"
           :multiple="true"
           :auto-upload="true"
         
          >
          
          <el-button slot="trigger" size="small" type="primary" :loading="upload.isUploading" >选取文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!pageDisabled">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <el-dialog
      :title="title"
      :visible.sync="openUpdate"
      width="800px"
      append-to-body
      @close="pageClose"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :disabled="pageDisabled"
        label-width="190px"
      >
         <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="文件名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!pageDisabled">
        <el-button type="primary" @click="submitFormUpdate">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>





  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  listFileInfo,
  getDownloadInfo,
  getFileInfo,
  delFileInfo,
  addFileInfo,
  updateFileInfo,
  exportFileInfo,
} from "@/api/grc/fileInfo";
const grcMajorId = "majorId";
export default {
  props: {
    detailDialog: {
      type: Object,
      default: function () {
        return {
          // 关联的id
          id: null,
          open: null,
          // 是否详情页
          isDisabled: null,
        };
      },
    },

    majorTableDate: {
      type: Object,
      default: function () {
        return {
          //管理的表明
          tableName: null,
        };
      },
    },

  },

  name: "FileInfo",
  data() {
    return {

      // 上传参数
        upload: {
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload",
          // 上传的文件列表
          fileList: [],
          addFileList: []
        },

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 附件信息表格数据
      fileInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openUpdate :false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        filePath: null,
        fileSize: null,
      
        majorName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        
      },
      thisDialogformIsDisabled: false,
    };
  },

  computed: {
    pageDisabled: function () {
      if (this.detailDialog.isDisabled) {
        return this.detailDialog.isDisabled;
      } else {
        return this.thisDialogformIsDisabled;
      }
    },
  },

  created() {
    this.getList();
  },

  watch: {
    /* 监听打开状态 */
    "detailDialog.open": function (newOpen, oldOpen) {
      //显示则刷新
      if (newOpen) {
        console.log(this.$options.name + "监听打开状态", this.detailDialog.id);
        this.getList();
      }
    },
  },

  methods: {

      // 文件下载处理
      handleDownload(row) {
          let fileName =row.fileName;
          let url = row.filePath;
          let xhr = new XMLHttpRequest();
          // get post
          xhr.open('get',url)
          //如果需要请求头中这是token信息可以在这设置
          xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8')
         // xhr.setRequestHeader('Authorization',"Bearer " + getToken())
          xhr.responseType = 'blob'
          xhr.onreadystatechange = function(){
            if(xhr.readyState ===4 && xhr.status === 200){
              const blob = new Blob([xhr.response])
              let url = window.URL.createObjectURL(blob)
              //创建一个a标签元素，设置下载属性，点击下载，最后移除该元素
              let link = document.createElement('a')
              link.href = url
              link.style.display = 'none'
              const downlaodFileName = decodeURIComponent(fileName)
              // console.log(fileName)
              // console.log(downlaodFileName)
              link.setAttribute('download',downlaodFileName)
              link.click()
              window.URL.revokeObjectURL(url)
            }
          }
           xhr.send();
      },

       handleDownload2(row) {
          let url=process.env.VUE_APP_BASE_API + "/grc/fileInfo/download/"+row.fileId
          let xhr = new XMLHttpRequest();
          // get post
          xhr.open('get',url)
          //如果需要请求头中这是token信息可以在这设置
          xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8')
          xhr.setRequestHeader('Authorization',"Bearer " + getToken())
          xhr.responseType = 'blob'
         
          xhr.onreadystatechange = function(){
            if(xhr.readyState ===4 && xhr.status === 200){
              const blob = new Blob([xhr.response])
              let url = window.URL.createObjectURL(blob)
              //创建一个a标签元素，设置下载属性，点击下载，最后移除该元素
              let link = document.createElement('a')
              link.href = url
              link.style.display = 'none'
              //取出下载文件名
              //const fileName = xhr.getResponseHeader('filename')
              //attachment;fileName=IOC.jpg
              //console.log(disposition)
               const disposition = xhr.getResponseHeader('content-disposition')
               const fileName = disposition.substring(20,disposition.length);
              const downlaodFileName = decodeURIComponent(fileName)
        
              link.setAttribute('download',downlaodFileName)
              link.click()
              window.URL.revokeObjectURL(url)
            }
          }
           xhr.send();
      },


       // 文件点击提交处理
        submitUpload() {
          this.$refs.upload.submit();
        },

      //选择已有文件显示
      handlePreview(file){
           //console.log(file.uid,file.size,file.name);
      },

     
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
        },
        //删除之前
        beforeRemove(file, fileList) {
         let isRemove=    this.$confirm("确认关闭？")
          .then((_) => {

               
               let index= this.upload.addFileList.findIndex(item=>{
                return  item.uid==file.uid
              });
             
              this.upload.addFileList.splice(index,1) 
          })
          
          
          
          return isRemove;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
          this.upload.isUploading = false;
          let addurl = response.url;
          let addfile={
                  filePath:addurl,
                  fileSize:file.size,
                  fileName:file.name,
                  uid:file.uid,
                  }
          this.upload.addFileList.push(addfile);
          //this.msgSuccess(response.msg);
        },

    /* 初始化DetailDialog */
    initDetailDialog() {
      this.queryParams[grcMajorId] = this.detailDialog.id;
    },

    /** 查询附件信息列表 */
    getList() {
      this.initDetailDialog();
      this.loading = true;
      listFileInfo(this.queryParams).then((response) => {
        this.fileInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
       this.openUpdate = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        fileName: null,
        filePath: null,
        fileSize: null,
        majorId: null,
        majorName: null,
        createBy: null,
        createTime: null,
        fileItemList :null,
      };
      this.resetForm("form");
      this.upload.addFileList=[];
      
      
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.fileId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加附件信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids;
      getFileInfo(fileId).then((response) => {
        this.form = response.data;
        this.openUpdate = true;
        this.title = "修改附件信息";
      });
    },

    /** 详情按钮操作 */
    handleDetail(row) {
      this.thisDialogformIsDisabled = true;
      this.reset();
      const fileId = row.fileId || this.ids;
      getFileInfo(fileId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改附件信息";
      });
    },
    pageClose() {
      this.thisDialogformIsDisabled = false;
    },

    /**修改提交 提交按钮 */
    submitFormUpdate(){
        this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.fileId != null) {
            updateFileInfo(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.fileId != null) {
            updateFileInfo(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
              if(this.upload.addFileList.length==0){
                  this.msgSuccess("请选择上传的文件");
                  return false;
              }
              this.form[grcMajorId] = this.detailDialog.id;
              this.form.majorName= this.majorTableDate.tableName;
              
              this.form.fileItemList=this.upload.addFileList
              addFileInfo(this.form).then((response) => {
                this.$refs.upload.clearFiles();
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$confirm(
        '是否确认删除附件信息编号为"' + fileIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delFileInfo(fileIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有附件信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportFileInfo(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
